#include "SignalControl.h"

SignalControl::SignalControl(RunConfig& data_a)
    : manager(new QNetworkAccessManager)
    , data_con(data_a)
{
    // 连接信号和槽
    connect(manager, &QNetworkAccessManager::finished, this, &SignalControl::handleReply);

}
SignalControl::~SignalControl(){
    delete manager;
}
//开始信号
void SignalControl::Start_signal(void){
    generate_uuid();//生成UUID

    //创建网络请求
    QNetworkRequest request;
    //组包
    QString a = "http://"+QString::fromStdString(data_con.getString("server_ip","127.0.0.1"))+":"+\
                QString::fromStdString(data_con.getString("port","80"))+"/SmokeService?"+\
                "action=startcheck&"+\
                "serial="+serial_num+"&"+\
                "linenum="+QString::fromStdString(data_con.getString("detection_line_num","001"));
    std::cout << "开始：" << a.toStdString() << std::endl;

    request.setUrl(QUrl(a));//设置请求的 URL
    
    //发送
    manager->get(request);

}
//停止信号
void SignalControl::Stop_signal(void){
    //创建网络请求
    QNetworkRequest request;
    //组包
    QString a = "http://"+QString::fromStdString(data_con.getString("server_ip","127.0.0.1"))+":"+\
                QString::fromStdString(data_con.getString("port","80"))+"/SmokeService?"+\
                "action=stopcheck&"+\
                "serial="+serial_num+"&"+\
                "linenum="+QString::fromStdString(data_con.getString("detection_line_num","001"));
    std::cout << "结束：" << a.toStdString() << std::endl;

    request.setUrl(QUrl(a));//设置请求的 URL
    
    //发送
    manager->get(request);

}
//生成UUID
void SignalControl::generate_uuid(void){
    serial_num = QUuid::createUuid().toString(QUuid::WithoutBraces).remove('-').toUpper();//

}
//清除UUID
void SignalControl::clear_uuid(void){
    serial_num = "";
}

void SignalControl::handleReply(QNetworkReply *reply) {
    if (reply->error()) {
        std::cerr << "网络错误：" << reply->errorString().toStdString() << std::endl;
    } else {
        const QByteArray responseBytes = reply->readAll();
        std::cout << "响应数据：" << responseBytes.constData() << std::endl;
    }

    reply->deleteLater(); // 一定要记得删除reply
}
